<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="../res/layui/css/layui.css">
</head>
<body>

    <div class="layui-fluid" style="padding: 10px">
      <fieldset class="layui-elem-field">
        <legend>图片上传</legend>
        <div class="layui-field-box">
          <div class="layui-upload">
            <button type="button" class="layui-btn" id="selectImg">
              <i class="layui-icon layui-icon-upload"></i> 选择图片
            </button>
            <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 11px;">
              预览图：
              <div class="layui-upload-list" id="upload-demo-preview"></div>
            </blockquote>
            <button class="layui-btn layui-bg-blue" id="uploadBtn">上传</button>
          </div>
        </div>
      </fieldset>
    </div>

    <script src="../res/layui/layui.js"></script>
    <script>
        layui.use(function(){
          //获取上传组件
          var upload = layui.upload;
          //获取jquery模块
          var $ = layui.jquery;
          //获取弹层组件
          var layer = layui.layer;

          //上传组件渲染
          upload.render({
            elem:'#selectImg',  //绑定触发选择文件（上传）元素
            url:'http://127.0.0.1:8080/image/upload', //服务器处理文件地址
            auto:false,         //关闭自动上传
            bindAction:'#uploadBtn',  //绑定触发上传操作的按钮元素
            multiple: true, //开启多文件上传
            field:'files', //绑定文件域名称（与服务器控制器方法参数名保持一致）
            choose: function(obj){   //绑定文件选择完成之后回调
              // 预读本地文件示例，不支持ie8
              obj.preview(function(index, file, result){
                $('#upload-demo-preview').append('<img src="'+ result +'" alt="'+ file.name +'" style="width: 90px; height: 90px;">')
              });
            },
            before:function(){
              //上传前显示加载层
              layer.load(2,{shade:0.5})
            },
            done:function(resp){
              //上传完毕后关闭所有加载层
              layer.closeAll('loading')
              if(resp.code === 0){
                layer.msg(resp.msg,function(){
                  location.reload();
                })
              }else{
                layer.alert(resp.msg,{icon:2})
              }
            }
          })

        })
    </script>
</body>
</html>